package com.syni.mdd.sjb.common.component.utils.common.quartz;
import lombok.extern.log4j.Log4j2;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;
import java.util.Map;

/**
 * @className QuartzDo
 * @description TOO
 * @Author cfx
 * @DATE 2019/7/8 9:44
 * @VERSION 1.0
 **/
@Log4j2
public class QuartzDo {
    private static Scheduler scheduler;

    static {
        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }
    }

    public static void setTask(Class classes, String jobName, String triggerName,
                               Date startTime, Map<String,Object> extra){
        try {
            JobDetail job1 = JobBuilder.newJob(classes)
                    .withIdentity(jobName, "default")
                    .build();
            if(QuartzDo.getScheduler().checkExists(job1.getKey())){
                QuartzDo.getScheduler().deleteJob(job1.getKey());
            }
            job1.getJobDataMap().putAll(extra);
            SimpleTrigger trigger1 = (SimpleTrigger) TriggerBuilder.newTrigger()
                    .withIdentity(triggerName, "default")
                    .startAt(startTime)
                    .build();
            QuartzDo.addJobToScheduler(job1,trigger1);
            QuartzDo.getScheduler().start();
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }
    }

    public static void addJobToScheduler(JobDetail job, SimpleTrigger trigger) {
        try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }
    }

    public static Scheduler getScheduler() {
        return scheduler;
    }
}
